local Archy = LibStub("AceAddon-3.0"):NewAddon("Archy",  "AceConsole-3.0", "AceEvent-3.0", "AceTimer-3.0", "LibSink-2.0")
local L = LibStub("AceLocale-3.0"):GetLocale("Archy", false)
local QT = LibStub("LibQTip-1.0");
local LSM = LibStub("LibSharedMedia-3.0")
Archy.version = GetAddOnMetadata("Archy", "Version")
local ldb = LibStub("LibDataBroker-1.1"):NewDataObject("Archy", {
	type = "data source",
	icon = "Interface\\Icons\\trade_archaeology",
	text = L["Archy"],
	label = L["Archy"],
	version = Archy.version,
	align = "right",
	["X-Category"] = "Information",
})
local icon = LibStub("LibDBIcon-1.0")
	
_G["Archy"] = Archy

-- locals
local DEBUG = true
local db
--local archdbs
-- Defaults for storage
local floor = floor
local next = next

local function dump_table(t)
	for key,value in pairs(t) do
		if type(value) == "table" then
			print("start of " .. key .. " table")
			dump_table(value)
			print ("end of " .. key .. " table");
		elseif type(value) == "userdata" then
		else
			print(key .. '=' .. value or "nil")
		end
	end
end


--[[
	Setup
]]
function Archy:OnInitialize()

	self.defaults = {
		profile = {
			general = {
				show = true,
				lock = false,
				icon = { 
					hide = false,
				},
				showRank = true,
			},
			ldb = {
				statistics = false,
				artifacts = true,
				digsites = true,
				filterDigsites = true,
			},
			digsites = {
				show = true,
				alpha = 1.0,
				scale = 1.0,
				sortByDistance = true,
				showCounter = true,
				showDistance = false,
				showZone = true,
				location = { x = 0, y = 0 },
				backgroundColor = { Red = 0, Green = 0, Blue = 0, Alpha = 0 },
				headerBackgroundColor = { Red = 0, Green = 0, Blue = 0, Alpha = 0 },
				headerMedia = { 
					font = "Friz Quadrata TT",
					height = 20,
					fontOutline = "",
					fontColor = { Red = 0.93, Green = 0.82, Blue = 0, Alpha = 1},
					fontSize = 12,
				},
				rowMedia = {
					font = "Friz Quadrata TT",
					height = 22,
					fontOutline = "",
					fontColor = { Red = 1, Green = 1, Blue = 1, Alpha = 1},
					fontSize = 12,
				},
			},
			artifacts = {
				show = true,
				alpha = 1.0,
				scale = 1.0,
				announce = true,
				keystoneAnnounce = false,
				ping = true,
				keystonePing = false,
				filter = true,
				blacklist = {},
				location = { x = 0, y = 0 },
				confirmSolve = true,
				backgroundColor = { Red = 0, Green = 0, Blue = 0, Alpha = 0 },
				headerBackgroundColor = { Red = 0, Green = 0, Blue = 0, Alpha = 0 },
				headerMedia = { 
					font = "Friz Quadrata TT",
					height = 20,
					fontOutline = "",
					fontColor = { Red = 0.93, Green = 0.82, Blue = 0, Alpha = 1},
					fontSize = 12,
				},
				rowMedia = {
					font = "Friz Quadrata TT",
					height = 22,
					fontOutline = "",
					fontColor = { Red = 1, Green = 1, Blue = 1, Alpha = 1},
					rareFontColor = { Red = 0, Green = 0.5, Blue = 0.9, Alpha = 1},
					grayFontColor = { Red = 0.5, Green = 0.5, Blue = 0.5, Alpha = 1},
					keystoneFontColor = { Red = 1, Green = 1, Blue = 0, Alpha = 1},
					fontSize = 12,
				},
			},
			minimap = {
				show = true,
				nearest = false,
				fragmentNodes = true,
				fragmentIcon = "cyandot",
				blob = false,
				battlemapBlob = false,
				blobAlpha = 0.5,
			},
			tomtom = {
				enable = false,
				arrivalDistance = 125,
				arrivalPing = false,
			},
			surveyIndicator = {
				enable = true,
				location = { x = 0, y = 0 },
				scale = 1.0,
				alpha = 1.0,
				greenDistance = 30,
				yellowDistance = 70,
				redDistance = 100
			},
		},
	}

	self.db = LibStub("AceDB-3.0"):New("ArchyDB", self.defaults, "Default")
	self.db.RegisterCallback(self, "OnProfileChanged", "OnProfileChanged")
	self.db.RegisterCallback(self, "OnProfileCopied", "OnProfileChanged")
	self.db.RegisterCallback(self, "OnProfileReset", "OnProfileChanged")

	self.archData = LibStub("LibArchaeology-0.1")
	
	self.astrolabe = DongleStub("Astrolabe-1.0")
	self.astrolabe.MinimapUpdateTime = 0.1;
	
	self.lsm = LSM
	self.lsm.RegisterCallback(self, "LibSharedMedia_Registered", "UpdateUsedMedia")

	
	if type(self.db.profile.general.icon) == "boolean" then
		self.db.profile.general.icon = { hide = false }		-- reset the invalid libdbicon savedvar to fix the bug related to it
	end

	
	self.races = {}
	self.currencies = {}
	self.racesLoaded = false
	self.solvedArtifact = nil
	self.lastSite = nil

	icon:Register("ArchyLDB", ldb, self.db.profile.general.icon)
	self.icon = icon

	-- Setup our saved vars, we dont use AceDB as it's over kill
	db = self.db.profile
end

function Archy:UpdateUsedMedia(event, mediatype, key)
	if mediatype == "statusbar" then
	elseif mediatype == "font" then
--		if key == db.artifacts.
	elseif mediatype == "background" then
	elseif mediatype == "border" then
	end
end

function Archy:OpenOptions()
	InterfaceOptionsFrame_OpenToCategory(Archy.options)
end

function Archy:ShowArchaeology()
	if IsAddOnLoaded("Blizzard_ArchaeologyUI") then
		ShowUIPanel(ArchaeologyFrame)
		return true
	else
		local loaded, reason = LoadAddOn("Blizzard_ArchaeologyUI")
		if loaded then
			ShowUIPanel(ArchaeologyFrame)
			return true
		else
			self:Print(string.format(L["ArchaeologyUI not loaded: %s Try opening manually."], _G["ADDON_"..reason]))
			return false
		end
	end
end



function Archy:OnProfileChanged(db, name)
	db = self.db.profile
	Archy:SendMessage("ArchyConfigChanged")
end

function Archy:RankDisplay()
	local header
	local rank, maxrank =  self.archData:GetArchaeologyRank()
	if rank and maxrank then
		if rank <=  self.maxArchaeologySkill then
			if maxrank < self.maxArchaeologySkill and (rank + 25) >= maxrank then
				header = string.format("|cFFFFFFFF%d|r/|cFFFFFFFF%d|r", rank, maxrank) .. " - |cFFFF0000" .. L["Visit a trainer"] .. "|r"
			else
				header = string.format("|cFFFFFFFF%d|r/|cFFFFFFFF%d|r", rank, maxrank)
			end
		end
	else
		header = "|cFFFF0000" .. L["Learn Archaeology"] .. "|r"
	end
	return header
end

--[[
	DataBroker
]]
function ldb:OnClick(button)
	if button == "LeftButton" and IsShiftKeyDown() then
		Archy:SendMessage("ArchyStealthMode")
	elseif button == "LeftButton" and IsControlKeyDown() then
		Archy:OpenOptions()
	elseif button == "LeftButton" then
		Archy:ToggleShowHide()
	elseif button == "RightButton" then
		Archy:ToggleLock()
	elseif button == "MiddleButton" then
		Archy:ShowArchaeology()
	end
end
function ldb:OnEnter()
	Archy:SendMessage("ArchyLDBTooltip", self)
end
function ldb:OnLeave()
	if not QT then return end
	QT:Release(self.tooltip)
	self.tooltip = nil
end


function Archy:ToggleLock()
	Archy.db.profile.general.lock = not Archy.db.profile.general.lock
	Archy:SendMessage("ArchyConfigChanged")
end

function Archy:ToggleShowHide()
	Archy.db.profile.general.show = not Archy.db.profile.general.show
	Archy:SendMessage("ArchyConfigChanged")
end

